package com.je21121.filter;

import com.sun.deploy.net.HttpRequest;
import com.sun.deploy.net.HttpResponse;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

import static javax.swing.text.html.CSS.getAttribute;

@WebFilter("/*")
public class MyFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //  每次请求之前 先会进入此方法中
        //   统一 编码
        HttpServletRequest httpRequest = (HttpServletRequest) servletRequest;
        httpRequest.setCharacterEncoding("utf-8");
        HttpServletResponse httpResponse = (HttpServletResponse) servletResponse;
        httpResponse.setCharacterEncoding("utf-8");
        //  获取当前请求地址
        String uri = httpRequest.getRequestURI();
        System.out.println(uri);
        //StringBuffer requestURL = httpRequest.getRequestURL();
        if(uri.contains("LoginController") || uri.contains(".css") || uri.contains(".js") ||  uri.contains(".html")){
            //  登录请求  直接放行
            filterChain.doFilter(httpRequest,httpResponse);
        }else{
            // 是否登录  已经登录  直接放行
            // 没有登录  重新返回到登录页面
            HttpSession session = httpRequest.getSession();
            Object userInfo = session.getAttribute("userInfo");
//            System.out.println(userInfo);
//            System.out.println(httpRequest.getSession().getMaxInactiveInterval());
            if(userInfo == null){
                //  没有登录  登录失效
                httpRequest.getRequestDispatcher("/login.html").forward(httpRequest,httpResponse);
            }else{
                //  重新设置成30秒
                //session.setMaxInactiveInterval(30);
                //  登录成功  放行
                filterChain.doFilter(httpRequest,httpResponse);
            }
        }

    }

    @Override
    public void destroy() {

    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }
}
